<template>
  <div class="quiz-questions-wrapper">
    <van-row v-if="questions">
      <span>
        {{ CONSTANTS.LABEL_STARTQUIZ }}{{ currentQuestionIdx + 1 }}/{{
          questionsLength
        }}
      </span>
      <p>{{ currentQuestion.question }}</p>
      <p
        v-for="item in answersWith"
        :key="`${item.answer}-${item.score}`"
        @click="onClk(item)"
        :style="[item.isActive ? activeAnswerStyle : '']"
      >
        <i>{{ item.answer }}</i>
      </p>
      <button-comp
        v-if="activeScore"
        :text="CONSTANTS.LABEL_SUBMIT"
        :style="buttonStyle"
        @click="onSubmit"
      />
    </van-row>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import * as CONSTANTS from '@/constants/index'
import QUESTIONS from '@/assets/quiz/index'
import TYPERELATION from '@/assets/quiz/type-relation'
import ButtonComp from '@/components/ButtonComp'
export default {
  props: {},
  components: { ButtonComp },
  data() {
    return {
      CONSTANTS: Object.freeze(CONSTANTS),
      QUESTIONS: Object.freeze(QUESTIONS),
      buttonStyle: {
        width: '83%',
        position: 'fixed',
        bottom: '22px',
        left: '50%',
        transform: 'translateX(-50%)',
      },
      activeAnswerStyle: {
        'background-color': 'rgba(255, 102, 102, 0.06)',
        border: 'solid 1px #ff6666',
      },
      answers: [], //当前问题的对应答案
      activeScore: 0, //当前点击后的分数
    }
  },
  computed: {
    ...mapGetters(['common', 'user', 'quiz']),
    //当前达到第几题
    currentQuestionIdx() {
      if (!this.quiz) return 0
      return this.quiz.currentQuestionIdx
    },
    dateDuration() {
      if (!this.user) return 0
      return this.user.dateDuration
    },
    //获取对应的年龄段问题
    questions() {
      const dateDuration = this.dateDuration
      return this.QUESTIONS.find((item) => {
        const { min, max, questions } = item
        if (dateDuration < min) return false
        if (dateDuration > max) return false
        return true
      })
    },
    //重新组构数据
    questionsWith() {
      const { questions } = this.questions
      if (!questions) return false

      return Object.keys(questions).reduce((acc, curKey) => {
        let values = questions[curKey]
        let { listcommit, scorecommit } = TYPERELATION.find(
          (item) => item.type === curKey
        )
        let valuesWith = values.map((item) => ({
          listcommit,
          scorecommit,
          type: curKey,
          ...item,
        }))
        return [...acc, ...valuesWith]
      }, [])
    },
    //当前索引所指向的问题
    currentQuestion() {
      const idx = this.currentQuestionIdx
      return this.questionsWith[idx]
    },
    //当前问题的长度
    questionsLength() {
      return this.questionsWith.length
    },
    isFinal() {
      return this.currentQuestionIdx * 1 === this.questionsLength - 1
    },
    answersWith() {
      return this.answers.map((item) => {
        const { score } = item
        let isActive = score * 1 === this.activeScore
        return {
          ...item,
          isActive,
        }
      })
    },
  },
  mounted() {
    let data = window.sessionStorage.getItem(CONSTANTS.STORAGE_VUEX_STATE)
    data = JSON.parse(data)
    this.$store.replaceState(Object.assign({}, data))
    window.onbeforeunload = () =>
      this.store.commit(CONSTANTS.COMMIT_STORAGE_VUEXSTATE)
  },
  filters: {},
  watch: {
    //监听currentQuestion && 从而可以附带isActive变量
    currentQuestion: {
      immediate: true,
      deep: true,
      handler(v) {
        if (v && v.answers) this.answers = v.answers
      },
    },
  },
  methods: {
    async onClk(item) {
      const idx = this.currentQuestionIdx
      const { score } = item
      const currentQuestion = this.currentQuestion
      const { type, listcommit, scorecommit } = currentQuestion

      //已经选择了最后一题，禁止重复点击
      if (this.activeScore) return console.log(`user have chosen answer.`)

      //最后一题时，将对应分数chosen，高亮对应的答案
      if (idx * 1 === this.questionsLength - 1) this.activeScore = score

      this.$store.commit(CONSTANTS[listcommit], score)

      let list = this.quiz[type]
      let sum = list.length ? list.reduce((prev, cur) => cur + prev) : 0
      let avg = list.length ? Math.round(sum / list.length) : 0
      this.$store.commit(CONSTANTS[scorecommit], avg)

      // 最后一题之后，不再增加index
      if (idx * 1 === this.questionsLength - 1) return console.log('-- final')
      await this.$nextTick()
      setTimeout(() => {
        this.$store.commit(
          CONSTANTS.COMMIT_UPDATE_QUESTION_ACTIVEINDEX,
          idx * 1 + 1
        )
      }, 100)
      this.$store.commit(CONSTANTS.COMMIT_STORAGE_VUEXSTATE)
    },
    async onSubmit() {
      let token = this.common.token
      if (!token) return console.log('token is null')

      //上传评测结果
      let res = await this.$store.dispatch(CONSTANTS.DISPATCH_POST_QUIZRESULT)
      this.$store.commit(CONSTANTS.COMMIT_STORAGE_VUEXSTATE)

      //获取历史记录
      await this.onGetHistoryList()

      await this.$nextTick()
      this.$store.dispatch(CONSTANTS.DISPATCH_REDIRECT, {
        path: '/quiz/report',
        isRouter: true,
      })
    },
    async onGetHistoryList() {
      const babyId = this.user.currentBabyId
      await this.$store.dispatch(CONSTANTS.DISPATCH_GETASYNC_HISTORYLIST, {
        babyId,
      })
      this.$store.commit(CONSTANTS.COMMIT_STORAGE_VUEXSTATE)
    },
  },
}
</script>

<style lang="less" scoped>
.quiz-questions-wrapper {
  & > div:first-of-type {
    width: 92%;
    margin: 0 auto;
    border-top: 13px solid transparent;
    & > span {
      line-height: 13px;
      font-family: 'SourceHanSansCN-Normal';
      font-size: 13px;
      font-weight: normal;
      font-stretch: normal;
      letter-spacing: 0px;
      color: rgba(0, 0, 0, 0.5);
    }

    & > p:first-of-type {
      margin-top: 36px;
      line-height: 26px;
      font-family: 'SourceHanSansCN-Medium';
      font-size: 20px;
      font-weight: normal;
      font-stretch: normal;
      letter-spacing: 0px;
      color: rgba(0, 0, 0, 0.8);
    }

    & > p:not(:first-of-type) {
      margin: 0 auto;
      margin-top: 22px;
      width: 92%;
      height: 48px;
      border-radius: 26px;
      border: solid 1px rgba(0, 0, 0, 0.15);
      display: flex;
      justify-content: center;
      align-items: center;
      & > i {
        font-style: normal;
        display: inline-block;
        line-height: 17px;
        font-family: 'SourceHanSansCN-Regular';
        font-size: 17px;
        font-weight: normal;
        font-stretch: normal;
        letter-spacing: 0px;
        color: rgba(0, 0, 0, 0.8);
      }
    }

    & > p:nth-of-type(2) {
      margin-top: 78px;
    }

    & > p:not(:first-of-type):active {
      background-color: rgba(255, 102, 102, 0.06);
      border: solid 1px #ff6666;
    }
  }
}
</style>
